# coding=utf-8

from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
import urllib
import json
from distribute import distribute
from base.Result import SuccessResult, ErrorResult


class ServerHTTP(BaseHTTPRequestHandler):
    def do_GET(self):
        path = self.path
        print path
        # 拆分url(也可根据拆分的url获取Get提交才数据),可以将不同的path和参数加载不同的html页面，或调用不同的方法返回不同的数据，来实现简单的网站或接口
        query = urllib.splitquery(path)
        print query
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.send_header("test", "This is test!")
        self.end_headers()
        buf = query
        self.wfile.write(buf)

    def do_POST(self):
        # 获取路径
        path = self.path
        # 获取post提交的数据
        # 读取body数据
        datas = self.rfile.read(int(self.headers['content-length']))
        datas = urllib.unquote(datas).decode("utf-8", 'ignore')
        print path, datas
        datas = json.loads(datas)

        self.send_response(200)
        self.send_header("Content-type", "application/json")
        self.end_headers()
        # try:
        result = SuccessResult(distribute(path, datas))
        # except Exception as e:
        #     print(e)
        #     result = ErrorResult(e.message)
        self.wfile.write(result.to_json())


def start_server(port):
    http_server = HTTPServer(('', int(port)), ServerHTTP)
    http_server.serve_forever()
    print "服务已启动"


if __name__ == "__main__":
    start_server(8000)
